package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.component.Connector;
import server.container.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap4 {

    private static Server server = new Server();

    //流程简述：
    // 1.加载server.xml，装配server对象及其子容器和组件，
    // 2.装配过程中定位webapps目录，初始化urlclassloader，加载不同目录下class
    // 3.读取对应目录下的web.xml，对servlet进行实例化，
    // 4。装配完成，
    // 5。请求到达根据url匹配获得对应webapp的servlet，并调用

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        //先加载server.xml配置信息
        loadServerConf();

//        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
//
        int port = server.getService().getConnector().getPort();
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
//
//
//        System.out.println("=========>>>>>>使用线程池进行多线程改造");
//        /*
//            多线程改造（使用线程池）
//         */
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,server);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }
    //加载server.xml配置文件，装配组件
    private void loadServerConf() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //装配Connector组件
            Service service = new Service();
            Element connEle = (Element) rootElement.selectSingleNode("//Connector");
            Integer port = Integer.parseInt(connEle.attributeValue("port"));
            Connector connector = new Connector(port);


            //装配Engine组件
            Engine engine = new Engine();
            Host host = new Host();
            Element hostEle = (Element) rootElement.selectSingleNode("//Host");
            host.setName(hostEle.attributeValue("name"));
            String appBase = hostEle.attributeValue("appBase");
            host.setAppBase(appBase);

            server.setService(service);
            service.setConnector(connector);
            service.setEngine(engine);
            engine.setHost(host);

            Context context = null;
            File workDir = new File(appBase);
            if (!workDir.exists()) {
                System.out.println("不存在该目录，请检查:"+workDir.getAbsolutePath());
                return;
            }else{
                File[] files = workDir.listFiles();
                for (File file : files) {
                    //过滤隐藏文件
                    if(!file.getName().contains(".")){
                        URL url = file.toURI().toURL();
                        //设置上下文容器的匹配路径context
                        context = new Context(url);
//                        Class<?> aClass = context.getClassLoader().loadClass("server.LagouServlet");
//                        HttpServlet servlet = (HttpServlet)aClass.newInstance();

                        File[] files1 = file.listFiles();
                        for (File f1 : files1) {
                            if(f1.getName().equalsIgnoreCase("web.xml")){
                                //解析web.xml
                                loadServlet(new FileInputStream(f1),context);
                                System.out.println("解析完成");
                            }
                        }
                        host.getContextMap().put("/"+file.getName(),context);
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(InputStream xmlInputStream,Context context) {
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(xmlInputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Wrapper wrapper = new Wrapper();
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                wrapper.setUrl(urlPattern);
                Servlet servlet = (Servlet)context.getClassLoader().loadClass(servletClass).newInstance();
                servlet.init();
                wrapper.setServlet(servlet);
                //将包装类放入map
                context.getMap().put(urlPattern,wrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap4 bootstrap = new Bootstrap4();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
